using System;
using Ext;
using Ext.data;
using Ext.form;

namespace PageScripts {
    public class SupplierDetailsForm : Ext.util.Observable {
        private Form _form;
        private LayoutDialog _dialog;
        private FormMode _mode;
        private Record _currentRecord;
        
        public SupplierDetailsForm() {
            addEvents(new Dictionary(
                "inserted", true,
                "updated", true
            ));
        }

        public void Show(FormMode mode, Element el, Record rec) {
            _mode = mode;
            if (Script.IsNullOrUndefined(_dialog)) Init();
            if (_dialog.isVisible()) _dialog.hide(null);

            if (_mode == FormMode.Update) {
                if (!Script.IsNullOrUndefined(rec)) {
                    _form.loadRecord(rec);
                    _currentRecord = rec;
                } else {
                    MessageBox.alert("Select a Supplier first ...", "please choose a supplier to update from the list.", null, null);
                    return;
                }
            } else {
                _currentRecord = null;
                _form.reset();
            }

            _dialog.show(el);
            _dialog.focus();
        }

        private void Init() {
            Script.Eval("Ext.form.Field.prototype.msgTarget = 'side'");
            Script.Eval("Ext.form.Field.prototype.focusClass = 'text-field-focus'");
            Script.Eval("Ext.form.Field.prototype.invalidClass = 'text-field-invalid'");
            
            TextField company = new TextField(new Dictionary("fieldLabel", "Company", "name", "CompanyName", "allowBlank", false));
            TextField contactName = new TextField(new Dictionary("fieldLabel", "Contact Name", "name", "ContactName", "allowBlank", false));
            TextField contactTitle = new TextField(new Dictionary("fieldLabel", "Contact Title", "name", "ContactTitle", "allowBlank", true));
            TextField phone = new TextField(new Dictionary("fieldLabel", "Phone", "name", "Phone", "allowBlank", false));
            TextField fax = new TextField(new Dictionary("fieldLabel", "Fax", "name", "Fax", "allowBlank", true));
            TextField homePage = new TextField(new Dictionary("fieldLabel", "Home Page", "name", "HomePage", "allowBlank", true));

            TextField address = new TextField(new Dictionary("fieldLabel", "Address", "name", "Address", "allowBlank", true));
            TextField city = new TextField(new Dictionary("fieldLabel", "City", "name", "City", "allowBlank", true));
            TextField region = new TextField(new Dictionary("fieldLabel", "Region", "name", "Region", "allowBlank", true));
            TextField postalCode = new TextField(new Dictionary("fieldLabel", "Postal Code", "name", "PostalCode", "allowBlank", true));
            TextField country = new TextField(new Dictionary("fieldLabel", "Country", "name", "Country", "allowBlank", true));


            _form = new Form(new Dictionary(
                "labelAlign", "left",
                "url", "DataHandler.aspx"
            ));
            // first column
            _form.column(new Dictionary(
                "width", 260,
                "labelWidth", 100,
                "style", "margin-left:8px;margin-top:8px"
            ));
            _form.fieldset(new Dictionary("id", "supplierContect", "legend", "Contact Info"), company, contactName, contactTitle, phone, fax, homePage);
            _form.end(); // close first column

            // second column
            _form.column(new Dictionary(
                "width", 260,
                "labelWidth", 100,
                "style", "margin-left:8px;margin-top:8px"
            ));
            _form.fieldset(new Dictionary("id", "supplierAddress", "legend", "Address"), address, city, region, postalCode, country);
            _form.end(); // close second column

            _form.applyIfToFields(new Dictionary("width", 135));
            _form.render("supplier-edit-form");

            _dialog = new LayoutDialog("supplier-edit-dialog", new Dictionary(
                "modal", false,
                "autoTabs", true,
                "proxyDrag", true,
                "width", 570,
                "height", 300,
                "shadow", true,
                "center", new Dictionary("autoScroll", true)
            ));
            _dialog.addButton("Save", new AnonymousDelegate(SaveData), this);
            _dialog.addButton("Cancel", new AnonymousDelegate(delegate() { _dialog.hide(null); }), _dialog);
            _dialog.addKeyListener(27, new AnonymousDelegate(delegate() { _dialog.hide(null); }), _dialog);

            BorderLayout layout = _dialog.getLayout();
            layout.beginUpdate();
            layout.add("center", new ContentPanel("supplier-edit-layout", new Dictionary("title", "Insert Supplier"), null));
            layout.endUpdate(false);
        }

        private void SaveData() {
            if (_mode == FormMode.Insert) {
                InsertSupplier();
            } else if (_mode == FormMode.Update) {
                UpdateSupplier();
            }
        }

        private void UpdateSupplier() {
            if (!_form.isValid()) {
                MessageBox.alert("Invalid Information", "<br />Please correct the invalid fields<br />", null, null);
                return;
            }
            _form.submit(new Dictionary(
                "waitMsg", "Saving Supplier ...",
                "reset", false,
                "params", new Dictionary("action", "UpdateSupplier", "SupplierID", _currentRecord.get("SupplierID")),
                "scope", this,
                "failure", new FormSubmitDelegate(delegate(Form form, Action action) {
                    MessageBox.alert("Error!", "There were errors saving this basket. <br />Please correct the errors and try again.", null, null);
                    fireEvent("updated", this, false, null);
                }),
                "success", new FormSubmitDelegate(delegate(Form form, Action action) {
                    _dialog.hide(null);
                    Dictionary newValues = new Dictionary(
                        "SupplierID", _currentRecord.get("SupplierID"),
                        "CompanyName", _form.findField("CompanyName").getValue(),
                        "ContactName", _form.findField("ContactName").getValue(),
                        "ContactTitle", _form.findField("ContactTitle").getValue(),
                        "Phone", _form.findField("Phone").getValue(),
                        "Fax", _form.findField("Fax").getValue(),
                        "HomePage", _form.findField("HomePage").getValue(),
                        "Address", _form.findField("Address").getValue(),
                        "City", _form.findField("City").getValue(),
                        "Region", _form.findField("Region").getValue(),
                        "PostalCode", _form.findField("PostalCode").getValue(),
                        "Country", _form.findField("Country").getValue()
                    );
                    fireEvent("updated", this, true, newValues);
                })
            ));
        }

        private void InsertSupplier() {
            if (!_form.isValid()) {
                MessageBox.alert("Invalid Information", "<br />Please correct the invalid fields<br />", null, null);
                return;
            }
            _form.submit(new Dictionary(
                "waitMsg", "Creating New Supplier",
                "reset", true,
                "params", new Dictionary("action", "InsertSupplier"),
                "scope", this,
                "failure", new FormSubmitDelegate(delegate(Form form, Action action) {
                    MessageBox.alert("Error!", "There were errors saving this basket. <br />Please correct the errors and try again.", null, null);
                    fireEvent("inserted", this, false);
                }),
                "success", new FormSubmitDelegate(delegate(Form form, Action action) {
                    _dialog.hide(null);
                    fireEvent("inserted", this, true);
                })
            ));
        }

    }
    public class SupplierDetailsFormEvents {
        /// <summary>Fires when a new Supplier is inserted
        /// <pre><code>
        /// USAGE: ({bool} success)
        /// </code></pre>
        /// <list type="bullet">
        /// <item><term><b>success</b></term><description>true, if the insert was successful</description></item>
        /// </list>
        /// </summary>
        public static string inserted { get { return "inserted"; } }
        /// <summary>Fires when a Supplier is updated
        /// <pre><code>
        /// USAGE: ({bool} success, {Dictionary} newValues)
        /// </code></pre>
        /// <list type="bullet">
        /// <item><term><b>success</b></term><description>true, if the update was successful</description></item>
        /// <item><term><b>newValues</b></term><description>the new values entered into the form</description></item>
        /// </list>
        /// </summary>
        public static string updated { get { return "updated"; } }
    }

    public delegate void SupplierDetailsFormInsertedDelegate(SupplierDetailsForm form, bool success);
    public delegate void SupplierDetailsFormUpdatedDelegate(SupplierDetailsForm form, bool success, Dictionary values);
}
